package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.local.PreferencesManager
import com.fishingwithme.android.data.model.ApproveRuleItem
import com.fishingwithme.android.data.model.City
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class HarvestShowUiState(
    val isLoading: Boolean = false,
    val spotId: String? = null,
    val error: String? = null,
    val images: List<String> = emptyList(),
    val isRec: Boolean = false,
    val score: String = "",
    val harvestType: String = "",
    val fishTypes: List<String> = emptyList(),
    val comment: String = "",
    val rulesItems: List<ApproveRuleItem> = emptyList(),
    val isRulesLoading: Boolean = false
)

@HiltViewModel
class HarvestShowViewModel @Inject constructor(
    private val repository: FishingRepository,
    private val preferencesManager: PreferencesManager
) : BaseViewModel(preferencesManager) {

    private val _uiState = MutableStateFlow(HarvestShowUiState())
    val uiState: StateFlow<HarvestShowUiState> = _uiState.asStateFlow()
    fun loadApproveHarvest(id: String) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }

            try {
                repository.loadApproveHarvest(id).collect { response ->
                    response.fold(
                        onSuccess = { harvest ->
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    spotId = harvest.spotId,
                                    images = harvest.jsonHisPictures,
                                    isRec = harvest.isRec == 1,
                                    score = harvest.scoreVal.name,
                                    harvestType = harvest.harvestTypeVal.name,
                                    fishTypes = harvest.fishes.map { fish -> fish.name },
                                    comment = harvest.comment
                                )
                            }
                        },
                        onFailure = { exception ->
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    error = exception
                                        .message ?: "加载渔获信息失败"
                                )
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(
                        isLoading = false,
                        error = e.message ?: "加载渔获信息失败"
                    )
                }
            }
        }
    }
    fun loadHarvest(id: String) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }

            try {
                repository.loadHarvest(id).collect { response ->
                    response.fold(
                        onSuccess = { harvest ->
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    spotId = harvest.spotId,
                                    images = harvest.jsonHisPictures,
                                    isRec = harvest.isRec == 1,
                                    score = harvest.scoreVal.name,
                                    harvestType = harvest.harvestTypeVal.name,
                                    fishTypes = harvest.fishes.map { fish -> fish.name },
                                    comment = harvest.comment
                                )
                            }
                        },
                        onFailure = { exception ->
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    error = exception
                                        .message ?: "加载渔获信息失败"
                                )
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(
                        isLoading = false,
                        error = e.message ?: "加载渔获信息失败"
                    )
                }
            }
        }
    }
    fun searchCities(keyword: String, onResult: (List<City>) -> Unit) {
        viewModelScope.launch {
            try {
                repository.searchCities(keyword).collect { result ->
                    result.fold(
                        onSuccess = { cities ->
                            onResult(cities)
                        },
                        onFailure = { throwable ->
                            // Handle error silently or log it
                            println("Failed to search cities: ${throwable.message}")
                        }
                    )
                }
            } catch (e: Exception) {
                // Handle exception
                println("Exception while searching cities: ${e.message}")
            }
        }
    }

    fun loadRulesItems(ruleId: Int = 1) {
        viewModelScope.launch {
            _uiState.update { it.copy(isRulesLoading = true, error = null) }

            try {
                repository.getRulesItems(ruleId).collect { result ->
                    result.fold(
                        onSuccess = { rulesItems ->
                            _uiState.update {
                                it.copy(
                                    isRulesLoading = false,
                                    rulesItems = rulesItems,
                                    error = null
                                )
                            }
                        },
                        onFailure = { throwable ->
                            _uiState.update {
                                it.copy(
                                    isRulesLoading = false,
                                    error = throwable.message ?: "加载规则失败"
                                )
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(
                        isRulesLoading = false,
                        error = e.message ?: "未知错误"
                    )
                }
            }
        }
    }
    fun clearError() {
        _uiState.update { it.copy(error = null) }
    }
}